package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Paint;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.Config;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.CityHotMenu.HotCell;
import com.myapp.ruyixing.model.NearbyStores;
import com.myapp.ruyixing.model.NearbyStores.Store;
import com.myapp.ruyixing.model.Privilege;
import com.myapp.ruyixing.model.Privilege.PrivilegeItem;
import com.myapp.ruyixing.ui.SearchCityDistrictFragment.OnDistrictItemClickListener;
import com.myapp.ruyixing.ui.SearchCityMenuFragment.OnCategoryItemClickListener;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.BitmapLruCache;
import com.myapp.ruyixing.utils.UIUtils;

public class NearbyStoreActivity extends BaseActivity implements
		OnClickListener, OnItemClickListener, OnCategoryItemClickListener,
		OnDistrictItemClickListener {

	public static final String INTENT_KEY_TYPE = "type";
	public static final String INTENT_KEY_DISTIRCTID = "districtid";
	public static final String INTENT_KEY_DISTIRCT_NAME = "district_name";
	public static final String INTENT_KEY_TYPEID = "typeid";
	public static final String INTENT_KEY_TYPE_NAME = "type_name";

	public static final String INTENT_LATITUDE = "lat";
	public static final String INTENT_LONGTUDE = "lng";

	public static final String INTENT_KEY_TYPE_PRIVILEGE = "from_privilege";

	private MyListAdapter mListAdapter;
	private List<Object> mData;
	private ListView mListView;
	private View mEmptyView;

	private TextView mLocaitonView;
	private View mMenuLayout;
	private View mLoadingView;

	private TextView mDistanceTabView;
	private TextView mTypeTabView;
	private TextView mOrderTabView;

	private MenuState mMenuState = MenuState.NONE;

	private String mActiveDistance;
	private String mActiveType;
	private String mActiveOrder;
	private String mActiveDistrict;
	private boolean mIsPrivilege;

	private double mLat;
	private double mLng;

	private SearchCityMenuFragment mSearchCityMenuFragment;
	private DistanceMenuFragment mDistanceMenuFragment;
	private OrderMenuFragment mOrderMenuFragment;
	private SearchCityDistrictFragment mSearchCityDistrictFragment;

	private boolean mIsDistrictMode;

	private enum MenuState {
		NONE, DISTANCE, TYPE, ORDER
	}

	private RYHttpResponseHandler mHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			if (mIsPrivilege) {
				Privilege privilege = (Privilege) o;
				mData.clear();
				if (privilege.items != null) {
					mData.addAll(privilege.items);
				}
			} else {
				NearbyStores stores = (NearbyStores) o;
				mData.clear();
				if (stores.items != null) {
					mData.addAll(stores.items);
				}
			}
			mListAdapter.notifyDataSetChanged();
			mListView.setEmptyView(mEmptyView);
			hideLoading();
		}

		@Override
		public void onFailure(Throwable throwable) {
			hideLoading();
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_nearby_store);

		mActiveDistance = "0";
		mActiveOrder = "default";
		mActiveType = "";

		mActiveDistrict = getIntent().getStringExtra(INTENT_KEY_DISTIRCTID);
		String mDistrictName = getIntent().getStringExtra(
				INTENT_KEY_DISTIRCT_NAME);
		String mTypeId = getIntent().getStringExtra(INTENT_KEY_TYPEID);
		String mTypeName = getIntent().getStringExtra(INTENT_KEY_TYPE_NAME);
		mIsPrivilege = getIntent().getBooleanExtra(INTENT_KEY_TYPE_PRIVILEGE,
				false);
		String type = getIntent().getStringExtra(INTENT_KEY_TYPE);

		initViews();

		mLat = getIntent().getDoubleExtra(INTENT_LATITUDE, 0);
		mLng = getIntent().getDoubleExtra(INTENT_LONGTUDE, 0);
		if (mLat == 0 && mLng == 0) {
			if (Config.sMyLocation != null) {
				mLat = Config.sMyLocation.getLatitude();
				mLng = Config.sMyLocation.getLongitude();
			}
		}

		if ("assistant".equals(type)) {
			changeType("assistant", "商助");
		} else if ("entertainment".equals(type)) {
			changeType("entertainment", "娱");
		} else if ("food".equals(type)) {
			changeType("food", "吃");
		} else if ("hotel".equals(type)) {
			changeType("hotel", "住");
		} else if ("shopping".equals(type)) {
			changeType("shopping", "购");
		} else if ("driving".equals(type)) {
			changeType("driving", "行");
		} else if ("travel".equals(type)) {
			changeType("travel", "游");
		}
		if (!TextUtils.isEmpty(mActiveDistrict)) {
			mIsDistrictMode = true;
			mDistanceTabView.setText(mDistrictName);
			mActiveType = "food";

			loadData();
		} else if (!TextUtils.isEmpty(mTypeId)) {
			changeType(mTypeId, mTypeName);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		RYHttpClient.cancleRequest(this);
	}

	private void initViews() {
		mListView = (ListView) findViewById(android.R.id.list);
		mEmptyView = findViewById(android.R.id.empty);
		mData = new ArrayList<Object>();
		mListAdapter = new MyListAdapter(mData);
		mListView.setAdapter(mListAdapter);
		mListView.setOnItemClickListener(this);

		mLocaitonView = (TextView) findViewById(R.id.location);
		mDistanceTabView = (TextView) findViewById(R.id.distance);
		mTypeTabView = (TextView) findViewById(R.id.type);
		mOrderTabView = (TextView) findViewById(R.id.order);
		mLoadingView = findViewById(R.id.my_loading);

		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(this);

		mMenuLayout = findViewById(R.id.menus);

		mDistanceTabView.setOnClickListener(this);
		mTypeTabView.setOnClickListener(this);
		mOrderTabView.setOnClickListener(this);

		// if (Config.sMyLocation != null) {
		// mLocaitonView.setText(Config.sMyLocation.getStreet());
		// }
		mLocaitonView.setVisibility(View.GONE);

		if (mIsPrivilege) {
			((TitleBar) findViewById(R.id.title_bar))
					.setTitleText(getString(R.string.privilege_nearby_title));
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (position >= 0 && position < mData.size()) {
			Object item = mData.get(position);
			String storeId = null;
			if (item instanceof Store) {
				storeId = ((Store) item).merchant_id;
				ShopDetailActivity.startShopDetailActivity(this, storeId);
			} else if (item instanceof PrivilegeItem) {
				storeId = ((PrivilegeItem) item).id;
				DiscountDetailActivity.startDiscountDetailActivity(this,
						storeId);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_icon:
			finish();

			break;
		case R.id.distance:
			if (mMenuState == MenuState.DISTANCE) {
				closeMenu();
			} else {
				mMenuLayout.setVisibility(View.VISIBLE);
				if (!mIsDistrictMode) {
					if (mDistanceMenuFragment == null) {
						mDistanceMenuFragment = new DistanceMenuFragment();
					}
					getSupportFragmentManager().beginTransaction()
							.replace(R.id.menus, mDistanceMenuFragment)
							.commit();
				} else {
					if (mSearchCityDistrictFragment == null) {
						mSearchCityDistrictFragment = SearchCityDistrictFragment
								.getInstance(false);
					}
					getSupportFragmentManager().beginTransaction()
							.replace(R.id.menus, mSearchCityDistrictFragment)
							.commit();
				}
				mMenuState = MenuState.DISTANCE;
			}

			break;

		case R.id.type:
			if (mMenuState == MenuState.TYPE) {
				closeMenu();
			} else {
				mMenuLayout.setVisibility(View.VISIBLE);
				if (mSearchCityMenuFragment == null) {
					mSearchCityMenuFragment = SearchCityMenuFragment
							.getInstance(false);
				}
				getSupportFragmentManager().beginTransaction()
						.replace(R.id.menus, mSearchCityMenuFragment).commit();
				mMenuState = MenuState.TYPE;
			}

			break;

		case R.id.order:
			if (mMenuState == MenuState.ORDER) {
				closeMenu();
			} else {
				mMenuLayout.setVisibility(View.VISIBLE);
				if (mOrderMenuFragment == null) {
					mOrderMenuFragment = OrderMenuFragment
							.newOrderMenuFragment(!mIsPrivilege);
				}
				getSupportFragmentManager().beginTransaction()
						.replace(R.id.menus, mOrderMenuFragment).commit();
				mMenuState = MenuState.ORDER;
			}

			break;
		case R.id.signup:
			Toast.makeText(this, "报名成功", Toast.LENGTH_LONG).show();

			break;

		default:
			break;
		}
	}

	@Override
	public void onDistrictItemClicked(HotCell cell) {
		chagneDistrict(cell.id, cell.name);
	}

	@Override
	public void onItemClicked(HotCell cell) {
		changeType(cell.id, cell.name);
	}

	public void changeDistance(String distance, String newWord) {
		if (!mActiveDistance.equals(distance)) {
			mActiveDistance = distance;
			mDistanceTabView.setText(newWord);

			loadData();
		}

		closeMenu();
	}

	public void chagneDistrict(String district, String newWord) {
		if (!mActiveDistrict.equals(district)) {
			mActiveDistrict = district;
			mDistanceTabView.setText(newWord);

			loadData();
		}

		closeMenu();
	}

	public void changeType(String type, String newWord) {
		if (!mActiveType.equals(type)) {
			mActiveType = type;
			mTypeTabView.setText(newWord);

			loadData();
		}

		closeMenu();
	}

	public void changeOrder(String order, String newWord) {
		if (!mActiveOrder.equals(order)) {
			mActiveOrder = order;
			mOrderTabView.setText(newWord);

			loadData();
		}

		closeMenu();

	}

	private void closeMenu() {
		mMenuLayout.setVisibility(View.GONE);
		mMenuState = MenuState.NONE;
		android.support.v4.app.Fragment fragment = getSupportFragmentManager()
				.findFragmentById(R.id.menus);
		if (fragment != null) {
			getSupportFragmentManager().beginTransaction().remove(fragment)
					.commit();
		}
	}

	private void showLoading() {
		mLoadingView.setVisibility(View.VISIBLE);
	}

	private void hideLoading() {
		mLoadingView.setVisibility(View.GONE);
	}

	private void loadData() {
		showLoading();
		if (mIsPrivilege) {
			int intType = -1;
			try {
				intType = Integer.parseInt(mActiveType);
			} catch (Exception e) {
			}
			if ("assistant".equals(mActiveType)) {
				intType = 7;
			} else if ("entertainment".equals(mActiveType)) {
				intType = 5;
			} else if ("food".equals(mActiveType)) {
				intType = 1;
			} else if ("hotel".equals(mActiveType)) {
				intType = 2;
			} else if ("shopping".equals(mActiveType)) {
				intType = 6;
			} else if ("driving".equals(mActiveType)) {
				intType = 3;
			} else if ("travel".equals(mActiveType)) {
				intType = 4;
			}
			RYHttpClient.getPrivilege(this, mHandler, intType, mActiveDistance,
					mActiveOrder);
		} else {
			if (!TextUtils.isEmpty(mActiveDistrict)) {
				RYHttpClient.getNearbyStore(this, mHandler, null, mActiveType,
						mActiveOrder, mActiveDistrict, mLat, mLng);
			} else {
				RYHttpClient.getNearbyStore(this, mHandler, mActiveDistance,
						mActiveType, mActiveOrder, null, mLat, mLng);
			}
		}
	}

	private class ViewHolder {
		TextView mTitleView;
		TextView mPriceView;
		NetworkImageView mShopImage;
		TextView mDistanceView;
		ImageView mScoreView;
		TextView mLabelsView;
		View mCardIndicatorView;
		View mTicketIndicatorView;
		View mBenifitIndicatorView;

		TextView mTimeView;
		TextView mPopularityView;
		TextView mNormalPriceView;
		TextView mPrivilegePriceView;
		View mSignUpView;
	}

	private class MyListAdapter extends ArrayAdapter<Object> {

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;

		public MyListAdapter(List<Object> data) {
			super(NearbyStoreActivity.this, -1, data);
			mQueue = Volley.newRequestQueue(NearbyStoreActivity.this);
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				if (getItem(position) instanceof Store) {
					convertView = LayoutInflater.from(NearbyStoreActivity.this)
							.inflate(R.layout.shop_list_item, parent, false);

					ViewHolder holder = new ViewHolder();
					holder.mTitleView = (TextView) convertView
							.findViewById(R.id.text_shop_name);
					holder.mPriceView = (TextView) convertView
							.findViewById(R.id.text_average_cost);
					holder.mShopImage = (NetworkImageView) convertView
							.findViewById(R.id.image_shop);
					holder.mDistanceView = (TextView) convertView
							.findViewById(R.id.text_distance);
					holder.mScoreView = (ImageView) convertView
							.findViewById(R.id.score);
					holder.mLabelsView = (TextView) convertView
							.findViewById(R.id.text_keywords);
					holder.mCardIndicatorView = convertView
							.findViewById(R.id.img_ka);
					holder.mTicketIndicatorView = convertView
							.findViewById(R.id.img_quan);
					holder.mBenifitIndicatorView = convertView
							.findViewById(R.id.img_hui);

					convertView.setTag(holder);
				} else {
					convertView = LayoutInflater.from(NearbyStoreActivity.this)
							.inflate(R.layout.cell_privilege, parent, false);

					ViewHolder holder = new ViewHolder();
					holder.mTitleView = (TextView) convertView
							.findViewById(R.id.title);
					holder.mTimeView = (TextView) convertView
							.findViewById(R.id.time);
					holder.mPopularityView = (TextView) convertView
							.findViewById(R.id.popularity);
					holder.mNormalPriceView = (TextView) convertView
							.findViewById(R.id.normal_price);
					holder.mPrivilegePriceView = (TextView) convertView
							.findViewById(R.id.privilege_price);
					holder.mShopImage = (NetworkImageView) convertView
							.findViewById(R.id.image);
					holder.mNormalPriceView.getPaint()
							.setFlags(
									Paint.STRIKE_THRU_TEXT_FLAG
											| Paint.ANTI_ALIAS_FLAG);
					holder.mSignUpView = convertView.findViewById(R.id.signup);
					// holder.mSignUpView
					// .setOnClickListener(NearbyStoreActivity.this);

					convertView.setTag(holder);
				}
			}

			ViewHolder mHolder = (ViewHolder) convertView.getTag();

			String picurl;

			if (getItem(position) instanceof Store) {
				NearbyStores.Store item = (Store) getItem(position);
				mHolder.mTitleView.setText(item.merchant_name);
				int price = 0;
				try {
					price = Integer.parseInt(item.price);
				} catch (Exception e) {
				}
				if (price != 0) {
					mHolder.mPriceView.setText(getString(R.string.store_price,
							"" + price));
				} else {
					mHolder.mPriceView.setText("");
				}
				mHolder.mLabelsView.setText(item.keywords);
				mHolder.mScoreView.setImageLevel(item.score);
				long sDistance = item.distance;
				picurl = item.picurl;

				if (sDistance >= 0) {
					String distance = "";
					if (sDistance >= 1000) {
						if (sDistance >= 1000000) {
							distance = "999+km";
						} else {
							distance = String.format("%.1fkm",
									((double) sDistance) / 1000);
						}
					} else {
						distance = sDistance + "m";
					}
					mHolder.mDistanceView.setText(distance);
				}

				UIUtils.setViewVisibility(mHolder.mCardIndicatorView,
						"1".equals(item.card));
				UIUtils.setViewVisibility(mHolder.mTicketIndicatorView,
						"1".equals(item.ticket));
				UIUtils.setViewVisibility(mHolder.mBenifitIndicatorView,
						"1".equals(item.benefit));

			} else {
				PrivilegeItem item = (PrivilegeItem) getItem(position);
				mHolder.mTitleView.setText(item.name);
				String text = "人气：" + item.hots + "    报名：" + item.signup;
				Spannable wordtoSpan = new SpannableString(text);
				int assignStart = text.indexOf("报");
				wordtoSpan.setSpan(new ForegroundColorSpan(getResources()
						.getColor(R.color.text_normal_price)), 3,
						assignStart - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				wordtoSpan.setSpan(new ForegroundColorSpan(getResources()
						.getColor(R.color.text_normal_price)), assignStart + 3,
						text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				mHolder.mPopularityView.setText(wordtoSpan);
				mHolder.mTimeView.setText("活动时间：" + item.activitytime);
				mHolder.mNormalPriceView.setText(item.originalprice);
				mHolder.mPrivilegePriceView.setText(item.presentprice);

				picurl = item.picUrl;
			}
			if (!TextUtils.isEmpty(picurl)) {
				mHolder.mShopImage.setImageUrl(picurl, mImageLoader);
			}

			return convertView;
		}
	}
}
